import csv
from datetime import datetime

from sqlalchemy import exc
from fastapi import HTTPException, status

from models.models import FileStatistic, Statistic  # , DoctorsInfo
from db.db import async_session, AsyncSession


async def write_statistic_to_db(filename: str):
    """Записывает содержимое файла статистики в БД."""
    async with async_session() as session:
        file_stat = FileStatistic(filename=filename)
        session.add(file_stat)
        try:
            await session.commit()
        except exc.IntegrityError:
            await session.rollback()
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Файл уже существует в базе данных",
            )
        await session.refresh(file_stat)

        with open(f"download/{filename}", mode="r", encoding="utf-8") as file:
            reader = csv.DictReader(file)
            for row in reader:
                record = Statistic(
                    id_filename=file_stat.id,
                    year=int(row["year"]),
                    week=int(row["week"]),
                    modality=row["modality"],
                    type_locality=row["type"],
                    number=int(row["number"]),
                    date=datetime.strptime(row["date"], "%Y-%m-%d"),
                )
                session.add(record)
            await session.commit()


async def write_doctors_info_to_db(filename: str, session: AsyncSession):
    """Записывает содержимое файла данных о врачах в БД."""
    with open(f"download/{filename}", mode="r", encoding="utf-8") as file:
        reader = csv.DictReader(file)
        for row in reader:
            record = DoctorsInfo(
                name=row["name"],
                modality=row["modality"],
            )
            session.add(record)
        try:
            await session.commit()
        except exc.IntegrityError:
            await session.rollback()
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Данные о врачах уже существуют в базе данных",
            )
